﻿using System;
using System.Globalization;

namespace TrackIT.Common
{
    public enum WorkEntryType { Start, Stop, Date };

    public class WorkEntry
    {
        public DateTime? Start { get; set; }

        public DateTime? Stop { get; set; }

        public bool IsMantisTicket { get; set; }

        public WorkEntryType EntryType
        {
            get
            {
                if (Stop == null)
                {
                    if (string.IsNullOrEmpty(Task))
                        return WorkEntryType.Date;
                    return WorkEntryType.Start;
                }
                return WorkEntryType.Stop;
            }
        }

        private string _task;

        public string Task
        {
            get
            {
                return _task;
            }
            set
            {
                _task = value;
                CheckIsMantisTicket();
            }
        }

        public WorkEntry()
        {
            Start = null;
            Stop = null;
            Task = null;
            IsMantisTicket = false;
        }

        public WorkEntry(string task, DateTime? start, DateTime? stop)
        {
            Start = start;
            Stop = stop;
            Task = task;
        }

        private void CheckIsMantisTicket()
        {
            int mantisIssueNumber;
            if (Int32.TryParse(Task, out mantisIssueNumber))
            {
                // if the task is a number remove any preceeding zeros
                _task = mantisIssueNumber.ToString(CultureInfo.InvariantCulture);
                IsMantisTicket = true;
            }
        }

        public WorkEntry(string workEntry)
        {
            workEntry = workEntry.TrimEnd(' ');
            string[] logEntry = workEntry.Split(' ');

            Start = null;
            Stop = null;

            if (logEntry.Length == 2)
            {
                Start = DateTime.Parse(logEntry[1]);
            }
            if (logEntry.Length >= 3)
            {
                Start = DateTime.Parse(logEntry[2]);
                Task = logEntry[1];
            }
            if (logEntry.Length >= 4)
            {
                Stop = DateTime.Parse(logEntry[3]);
            }
        }

        public override bool Equals(object obj)
        {
            WorkEntry o = (obj as WorkEntry);
            return o != null &&
            (
                o.Task == Task &&
                o.EntryType == EntryType &&
                o.Start.Equals(Start) &&
                o.Stop.Equals(Stop)
            );
        }

        public override int GetHashCode()
        {
            return Task.GetHashCode() ^
                EntryType.GetHashCode() ^
                Start.GetHashCode() ^
                Stop.GetHashCode();
        }
    }
}